package com.smart.cosstarter.utils;

import java.io.*;

/**
 * @Author: jj
 * @Date: 2019/8/8 17:31
 * @Version 1.0
 */
public class FileUtils {
	//将文件转换成Byte数组
	public static byte[] getBytesByFile(File file) {
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			byte[] data = bos.toByteArray();
			bos.close();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	//将Byte数组转换成文件
	public static File getFileByBytes(byte[] bytes, String filePath, String fileName) {
		File dir = new File(filePath);
		if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
			dir.mkdirs();
		}
		String fileSeparator = System.getProperty("file.separator");
		String absolutePath = filePath + fileSeparator + fileName;
		return getFileByBytes(bytes, absolutePath);
	}

	//将Byte数组转换成文件
	public static File getFileByBytes(byte[] bytes, String absolutePath) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(absolutePath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			} else {
				file = new File(absolutePath);
			}
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
			return file;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}